﻿using DFGK.IRepository;
using DFGK.IService;
using DFGK.Service;
using DFGK_WMS.Common;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using NPOI.SS.Formula.Functions;
using System.Net.Mime;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Xml.Linq;
using Yitter.IdGenerator;

namespace DFGK_WMS.WebAPI.Controllers.PC.基础数据
{
    /// <summary>
    /// 仓位
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "PC")]
    public class CellController : BaseController
    {
        private readonly ICellService cellService;
        private readonly ICellRepository cellRepository;

        public CellController(IWebHostEnvironment environment, ICellService cellService, ICellRepository cellRepository) : base(environment)
        {
            this.cellService = cellService;
            this.cellRepository = cellRepository;
        }
        /// <summary>
        /// 添加仓位
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Addell(Model.Models.Cell obj)
        {
            if (string.IsNullOrEmpty(obj.Code) || obj.Code.Length <= 0)
            {
                return Ok(BaseResult.Result("400", "编码不能为空！"));
            }
            string message = "";
            obj.CreateUserId = base.BaseGetNowUserId();
            obj.CreateUserName = base.BaseGetNowUserName();
            bool result = cellService.AddCell(obj, out message);
            if (result)
            {
                return Ok(BaseResult.Result(result, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(result, "添加失败！" + message, "500"));
        }
        /// <summary>
        /// 修改仓位
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdCell(Model.Models.Cell obj)
        {
            if (obj.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            if (string.IsNullOrEmpty(obj.Code))
            {
                return Ok(BaseResult.Result("400", "必填项不能为空！"));
            }
            obj.ModifyUserId = base.BaseGetNowUserId();
            obj.ModifyUserName = base.BaseGetNowUserName();
            string message = "";
            bool result = cellService.UpdCell(obj, out message);
            if (result)
            {
                return Ok(BaseResult.Result(result, "修改成功！", "200"));
            }
            return Ok(BaseResult.Result(result, "修改失败！" + message, "200"));
        }
        /// <summary>
        /// 删除仓位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelCell(long id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }

            bool IsOK = cellService.DelCell(id);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }

        /// <summary>
        /// 仓位左侧树形显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenuitemList()
        {
            var mlist = cellService.GetMenuitem();

            if (mlist != null)
            {
                return Ok(BaseResult.Result(mlist, "获取成功！"));
            }

            return Ok(BaseResult.Result(null, "获取失败！"));
        }

        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="logicalPartCode"></param>
        /// <param name="fullStatus"></param>
        /// <param name="status"></param>
        /// <param name="cname"></param>
        /// <param name="whid"></param>
        /// <param name="areid"></param>
        /// <param name="sheid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCellList(string? logicalPartCode = "", int fullStatus = 3, int status = 8, string? cname = "", long whid = 0, long areid = 0, long sheid = 0, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                BaseResult.Result("400", "分页条件有误！");
            }
            int totalCount;
            var list = cellService.GetCellList(logicalPartCode, fullStatus, status, cname, whid, areid, sheid, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 根据id获取对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCellById(long id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var cobj = cellService.GetCellById(id);
            if (cobj != null)
            {
                return Ok(BaseResult.Result(cobj, "查询成功！", "200", 0));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));

        }

        /// <summary>
        /// 根据code获取对象
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCellByCode(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return Ok(BaseResult.Result("400", "必填项不能为空！"));
            }
            var cobj = cellService.GetCellByCode(code);
            if (cobj != null)
            {
                return Ok(BaseResult.Result(cobj, "查询成功！", "200", 0));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));

        }

        /// <summary>
        /// 批量生成仓位
        /// </summary>
        /// <param name="cellCreateBodyDTO"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BatchCreateCell(CellCreateBodyDTO cellCreateBodyDTO)
        {
            if (cellCreateBodyDTO.WhId.GetValueOrDefault() <= 0 || cellCreateBodyDTO.AreaId.GetValueOrDefault() <= 0 || cellCreateBodyDTO.ShelfIds == null || cellCreateBodyDTO.ShelfIds.Count <= 0)
            {
                return Ok(BaseResult.Result(false, "未选择库房或库区或货架", "500"));
            }
            if (cellCreateBodyDTO.MaxLayer <= 0)
            {
                return Ok(BaseResult.Result(false, "最大层数未设置", "500"));
            }
            if (cellCreateBodyDTO.MaxColumn <= 0)
            {
                return Ok(BaseResult.Result(false, "最大列数未设置", "500"));
            }
            string message = "";
            var isOk = cellService.BatchCreateCell(cellCreateBodyDTO, out message);
            if (isOk)
            {
                return Ok(BaseResult.Result(true, "批量添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /// <summary>
        /// 枚举高度类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmHeightType()
        {
            var list = BaseGetEnum.GetCodeRulesList<EmHeightType>();

            return Ok(list);
        }

        /// <summary>
        /// 仓位统计
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCellCount()
        {
            var cobj = cellService.GetCellCount();
            if (cobj != null)
            {
                return Ok(BaseResult.Result(cobj, "查询成功！", "200", 0));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 添加移库单时获取同巷道仓位
        /// </summary>
        /// <param name="arecode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTransferBinToCellList(string arecode)
        {
            if (string.IsNullOrEmpty(arecode))
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var list = cellService.GetTransferBinToCellList(arecode);
            return Ok(BaseResult.Result(list, "查询成功！", "200", 0));
        }
        /// <summary>
        /// 初始化盐城消防仓位
        /// </summary>
        /// <returns></returns>
        [HttpGet, Obsolete]
        public IActionResult CreateCellAll()
        {
            var aP = new List<int>()
            {
                1, 2,3,4,5,6,7,8,9,10,12,13,14,15
            };//不规则的排
            var bP = new List<int>()
            {
                23,24,25
            };//不规则的排
            var cellList = new List<Model.Models.Cell>();
            for (int c = 1; c <= 3; c++)
            {
                for (int l = 1; l <= 9; l++)
                {
                    for (int p = 1; p <= 25; p++)
                    {
                        var cell = new Model.Models.Cell()
                        {
                            Id = YitIdHelper.NextId(),
                            WhId = 551430736916485,
                            WhCode = "1",
                            WhName = "盐城消防立体库",
                            AreaId = 564478436073477,
                            AreaCode = "sp",
                            AreaName = "食品区",
                            RoutewayId = 552865016840197,
                            ShelfId = 552865266692101,
                            ShelfCode = "1",
                            ShelfName = "第一货架",
                            Status = 1,
                            LineNo = p,
                            LayerNo = c,
                            ColumnNo = l,
                            IsMaxDepth = false,//默认赋false下面代码会找出为true的仓位
                            IsLock = false,
                            FullStatus = 0,
                        };
                        if (l == 1)
                        {
                            cell.DepthIndex = 1;
                            cell.IsMaxDepth = true;
                        }
                        if (l == 2 || l == 7)
                            cell.DepthIndex = 0;

                        if (l == 3 || l == 6)//第七列是巷道
                            cell.Status = 7;

                        if (l == 4 || l == 5)
                        {
                            cell.DepthIndex = 0;
                            cell.IsMaxDepth = true;
                        }
                        if (l == 8)
                            cell.DepthIndex = 1;

                        //开始处理不规则的排
                        if (l == 8 && aP.Contains(p))
                        {
                            cell.IsMaxDepth = true;
                        }

                        if (l == 9)
                        {
                            if (bP.Contains(p))
                            {
                                cell.DepthIndex = 2;
                                cell.IsMaxDepth = true;
                            }
                            else
                            {
                                cell.Status = 7;
                            }
                        }


                        if ((p == 11 || p == 17 || p == 18 || p == 19 || p == 22) && l >= 3)
                        {
                            cell.Status = 7;
                        }
                        if (p == 16 && (l == 3 || l == 6 || l == 7 || l == 8 || l == 9))
                        {
                            cell.Status = 7;
                        }
                        if ((p == 20 || p == 21 || p == 22) && l >= 6)
                        {
                            cell.Status = 7;
                        }


                        cell.Name = $"{cell.LineNo}排{cell.ColumnNo}列{cell.LayerNo}层{cell.DepthIndex + 1}深位";
                        cell.Code = $"{cell.LineNo.ToString().PadLeft(2, '0')}0{cell.ColumnNo}0{cell.LayerNo}";

                        cellList.Add(cell);
                    }
                }
            }
            var result = cellService.AddCell(cellList);
            if (result)
            {
                return Ok(BaseResult.Result(result, "成功", "200"));
            }
            return Ok(BaseResult.Result(result, "失败", "500"));
        }
        /// <summary>
        /// 初始化仓位所属管理区
        /// </summary>
        /// <returns></returns>
        [HttpGet, Obsolete]
        public IActionResult UpdCellInit()
        {
            var result = false;
            //管理区
            var glPh = new List<int>()
            {
                22,23,24,25
            };
            var updCellGl = cellRepository.GetEntityWhereAll(s => glPh.Contains(s.LineNo)).ToList();
            foreach (var item in updCellGl)
            {
                item.AreaId = 564606388760581;
                item.AreaCode = "gl";
                item.AreaName = "管理区";
                item.ShelfId = 564676577411077;
                item.ShelfCode = "003";
                item.ShelfName = "管理货架";
                result = cellService.UpdCell(item, out string msg);
            }
            //医疗区
            var ylPh = new List<int>()
            {
                18,19,20,21
            };
            var updCellYl = cellRepository.GetEntityWhereAll(s => ylPh.Contains(s.LineNo)).ToList();
            foreach (var item in updCellYl)
            {
                item.AreaId = 564606635585541;
                item.AreaCode = "yl";
                item.AreaName = "医疗区";
                item.ShelfId = 564676836954117;
                item.ShelfCode = "005";
                item.ShelfName = "医疗货架";
                result = cellService.UpdCell(item, out string msg);
            }

            //食品区
            var spPh = new List<int>()
            {
                16,17
            };
            var updCellSp = cellRepository.GetEntityWhereAll(s => spPh.Contains(s.LineNo)).ToList();
            foreach (var item in updCellSp)
            {
                item.AreaId = 564478436073477;
                item.AreaCode = "sp";
                item.AreaName = "食品区";
                item.ShelfId = 552865266692101;
                item.ShelfCode = "001";
                item.ShelfName = "食品货架";
                result = cellService.UpdCell(item, out string msg);
            }

            //战勤区
            var zqPh = new List<int>()
            {
                8,9,10,11,12,13,14,15
            };
            var updCellZq = cellRepository.GetEntityWhereAll(s => zqPh.Contains(s.LineNo)).ToList();
            foreach (var item in updCellZq)
            {
                item.AreaId = 564606081716229;
                item.AreaCode = "zq";
                item.AreaName = "战勤区";
                item.ShelfId = 564676431765509;
                item.ShelfCode = "002";
                item.ShelfName = "战勤货架";
                result = cellService.UpdCell(item, out string msg);
            }

            //救援区
            var jyPh = new List<int>()
            {
                1,2,3,4,5,6,7
            };
            var updCellJy = cellRepository.GetEntityWhereAll(s => jyPh.Contains(s.LineNo)).ToList();
            foreach (var item in updCellJy)
            {
                item.AreaId = 564606493315077;
                item.AreaCode = "jq";
                item.AreaName = "救援区";
                item.ShelfId = 564676738502661;
                item.ShelfCode = "004";
                item.ShelfName = "救援货架";
                result = cellService.UpdCell(item, out string msg);
            }
            return Ok(BaseResult.Result(result, "成功", "200"));
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="layer"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCellByLayer([FromQuery] params int[] layer)
        {
            var list = cellService.GetCellByLayers(layer);
            return Ok(BaseResult.Result(list, "200"));
        }

        /// <summary>
        /// 根据层号获取该层所有仓位信息
        /// </summary>
        /// <param name="layer"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCellByLayers(int layer)
        {
            if (layer <= 0)
            {
                return Ok(BaseResult.Result("400", "必填项不能为空！"));
            }
            var list = cellService.GetCellByLayer(layer);

            return Ok(BaseResult.Result(list, "查询成功！", "200", 0));

        }

        
    }
}
